package health.lm.com.mine.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 城市选择弹窗
 */

public class PickCityUtil {
    private  Context context;
    private static MyHandler mHandler;
    private static pickCityListener pickCityListener;
    private ArrayList<CityJsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private HashMap<String,String> province = new HashMap<>();
    private HashMap<String,String> city = new HashMap<>();
    private HashMap<String,String> area = new HashMap<>();

    private static Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private OptionsPickerView pvOptions;

    public PickCityUtil(Context ctx){
        mHandler = new MyHandler((Activity) context);
        context = ctx;
        pickCityListener = (PickCityUtil.pickCityListener) ctx;
    }

    public void start(){
        if(options1Items.size()>0){
            mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
        }else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }


    public interface pickCityListener{
        void pickCityData(String province, String provinceId, String city, String cityId, String area, String areaId);
    }

    private  class MyHandler extends Handler {

        private WeakReference<Activity> reference;
        public MyHandler(Activity activity) {
            reference = new WeakReference<Activity>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            Activity theActivity = reference.get();
                switch (msg.what) {
                    case MSG_LOAD_DATA:
                        if (thread==null){//如果已创建就不再重新创建子线程了
                            thread = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    // 写子线程中的操作,解析省市区数据
                                    initJsonData();
                                }
                            });
                            thread.start();
                        }
                        break;

                    case MSG_LOAD_SUCCESS:
                        select();
                        thread =null;
                        break;

                    case MSG_LOAD_FAILED:
                        ToastUtils.showShort("解析数据失败");
                        break;
                }
            }
    }



    private void  select(){
        if(null == pvOptions) {
            pvOptions = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    String provineName = options1Items.get(options1).getName();
                    String cityName = options2Items.get(options1).get(options2);
                    String areaName = options3Items.get(options1).get(options2).get(options3);
                    pickCityListener.pickCityData(provineName, province.get(provineName), cityName, city.get(cityName), areaName, area.get(areaName));
                }
            })      .setTitleText("城市选择")
                    .setDividerColor(Color.BLACK)
                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                    .setContentTextSize(20)
                /*.setTypeface(Typeface.DEFAULT_BOLD)//加粗字体*/
                    .setOutSideCancelable(false)// default is true
                    .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/

            pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        }
        pvOptions.show();
    }
    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = JsonUtil.getJson(context,"region.json");//获取assets目录下的json文件数据

        ArrayList<CityJsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         */
        options1Items = jsonBean;

        for (int i=0;i<jsonBean.size();i++){//遍历省份
            province.put(options1Items.get(i).getName(),options1Items.get(i).get_id());
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c=0; c<jsonBean.get(i).getCity().size(); c++){//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCity().get(c).getName();
                city.put(CityName,jsonBean.get(i).getCity().get(c).get_id());
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空数据，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCity().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                }
                for (int d=0; d < jsonBean.get(i).getCity().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                    String AreaName = jsonBean.get(i).getCity().get(c).getArea().get(d).getName();
                    area.put(AreaName,jsonBean.get(i).getCity().get(c).getArea().get(d).get_id());
                    City_AreaList.add(AreaName);//添加该城市所有地区数据
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<CityJsonBean> parseData(String result) {//Gson 解析
        ArrayList<CityJsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                CityJsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), CityJsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
            e.printStackTrace();
        }
        return detail;
    }
}
